package com.stone.EasyTeaching.utilities;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.stone.EasyTeaching.ETApplication;
import com.stone.EasyTeaching.R;
import com.stone.EasyTeaching.events.BaseEvents;
import com.stone.EasyTeaching.events.EventsConfig;
import com.stone.EasyTeaching.utilities.photoview.PhotoViewAttacher;
import de.greenrobot.event.EventBus;

public class AlbumDetailFragment extends Fragment {
    private String mImageUrl;
    private ImageView mImageView;
    private ProgressBar progressBar;
    private PhotoViewAttacher mAttacher;
    private boolean isLocal = true;

    /**
     * 创建Fragment
     * @param imageUrl
     * @param isLocal 本地图片传true，网络图片传false
     * @return
     */
    public static AlbumDetailFragment newInstance(String imageUrl, boolean isLocal) {
        final AlbumDetailFragment f = new AlbumDetailFragment();
        final Bundle args = new Bundle();
        args.putString("url", imageUrl);
        args.putBoolean("isLocal", isLocal);
        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageUrl = getArguments() != null ? getArguments().getString("url") : null;
        isLocal = getArguments() != null ? getArguments().getBoolean("isLocal") : true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.image_detail_fragment,
                container, false);
        mImageView = (ImageView) v.findViewById(R.id.image);
        mAttacher = new PhotoViewAttacher(mImageView);

        mAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {

            @Override
            public void onPhotoTap(View arg0, float arg1, float arg2) {
                /**
                 * By hangli2 点击页面不能直接结束，为了方便后续操作在此发送消息
                 */
                EventBus.getDefault().post(new BaseEvents(EventsConfig.ALBUM_DETAIL_CLICK));
//                getActivity().finish();
            }
        });

        progressBar = (ProgressBar) v.findViewById(R.id.loading);
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
//        ImageLoader.getInstance().clearDiskCache();
        ImageLoader.getInstance().clearMemoryCache();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        //内存溢出的问题使用lagerheap解决，再也不崩溃了，简直人生赢家
        super.onActivityCreated(savedInstanceState);
        if (isLocal) {
            //对于本地文件需要进行处理
            mImageUrl = "file://" + mImageUrl;
        }
        if (mImageUrl == null) {
            progressBar.setVisibility(View.VISIBLE);
        }
        {//加载远程图片还是用ImageLoader，非常的可靠
            ImageLoader.getInstance().displayImage(mImageUrl, mImageView, ((ETApplication)getActivity().getApplication()).getLocalOptionsForThumb(), new SimpleImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    progressBar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason
                        failReason) {
                    String message = null;
                    switch (failReason.getType()) {
                        case IO_ERROR:
                            message = "网络连接不可用\n请检查网络设置";
                            break;
                        case DECODING_ERROR:
                            message = "图片无法显示";
                            break;
                        case NETWORK_DENIED:
                            message = "网络连接不可用\n请检查网络设置";
                            break;
                        case OUT_OF_MEMORY:
                            message = "图片太大无法显示";
                            break;
                        case UNKNOWN:
                            message = "未知的错误";
                            break;
                    }
                    Toast.makeText(getActivity(),message,Toast.LENGTH_SHORT).show();
//                    ToastUtil.showNoticeToast(getActivity(), message);
                    progressBar.setVisibility(View.GONE);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap
                        loadedImage) {
                    if (mImageUrl != null) {
                        progressBar.setVisibility(View.GONE);
                    }
                    mAttacher.update();
                }
            });
        }
    }

    /**
     * 手动加载
     * @param imageFilePath
     * @return
     */
    /* 获得图片，并进行适当的 缩放。 图片太大的话，是无法展示的。 */
    private Bitmap getBitMapFromPath(String imageFilePath) {
        Display currentDisplay = this.getActivity().getWindowManager()
                .getDefaultDisplay();
        int dw = currentDisplay.getWidth();
        int dh = currentDisplay.getHeight();
        // Load up the image's dimensions not the image itself
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        float options = 1.0f;
        if (bmpFactoryOptions.outHeight * bmpFactoryOptions.outWidth > 2000000) {
            options = (float) (bmpFactoryOptions.outHeight * bmpFactoryOptions.outWidth) / 2000000;
            bmpFactoryOptions.inSampleSize = (int) (Math.ceil(options));
        } else {
            bmpFactoryOptions.inSampleSize = 1;
        }

//        int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
//                / (float) dh);
//        int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
//                / (float) dw);
//
//        // If both of the ratios are greater than 1,
//        // one of the sides of the image is greater than the screen
//        if (heightRatio > 1 && widthRatio > 1) {
//            if (heightRatio > widthRatio) {
//                // Height ratio is larger, scale according to it
//                bmpFactoryOptions.inSampleSize = heightRatio;
//            } else {
//                // Width ratio is larger, scale according to it
//                bmpFactoryOptions.inSampleSize = widthRatio;
//            }
//        }
        // Decode it for real
        bmpFactoryOptions.inJustDecodeBounds = false;
        Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        int rotate = Util.getBitmapDegree(imageFilePath);
        if (rotate > 0) {
            Matrix matrix = new Matrix();
            matrix.setRotate(rotate);
            Bitmap rotateBitmap = Bitmap.createBitmap(
                    bmp, 0, 0, bmpFactoryOptions.outWidth, bmpFactoryOptions.outHeight, matrix, true);
            if (rotateBitmap != null) {
                bmp.recycle();
                bmp = rotateBitmap;
            }
        }

        return bmp;
    }

}
